package xyz.zhouzhaodong.crm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 文件上传工具类
 *
 * @author zhouzhaodong
 */
public class FileUploadUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);

    /**
     * 文件保存地址
     */
    private static final String FILE_ADDRESS = "/var/crm/upload/";
//    private static String FILE_ADDRESS = "F:/crm/";

    /**
     * 文件下载地址
     */
    private static final String FILE_DOWNLOAD = "http://122.51.202.242:8888/material/fileDowLoad?fileUrl=";
//    private static final String FILE_DOWNLOAD = "http://localhost:8888/material/fileDowLoad?fileUrl=";

    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    public static String uploadOneFile(MultipartFile file, String clientId) {

        String downLoadAddress = "";
        File file1 = new File(FILE_ADDRESS + clientId + "/");
        if (!file1.exists()) {
            // 新建文件夹
            boolean b = file1.mkdirs();
        }
        // 拼接新的文件名
        String finalFilePath = FILE_ADDRESS + clientId + "/" + Objects.requireNonNull(file.getOriginalFilename()).trim();
        File saveFile = new File(finalFilePath);
        if (saveFile.exists()) {
            // 已存在就删除之前的
            boolean b = saveFile.delete();
        }
        try {
            // 保存
            file.transferTo(saveFile);
            downLoadAddress = FILE_DOWNLOAD + finalFilePath ;
        } catch (Exception e) {
            logger.info("文件上传失败:" + e.getMessage());
        }
        return downLoadAddress;
    }

    /**
     * 多文件上传
     *
     * @param files
     * @return
     */
    public static List<String> uploadManyFile(MultipartFile[] files, String clientId) {
        List<String> picUrl = new ArrayList<>();
        File saveDir = new File(FILE_ADDRESS + clientId + "/");
        if (!saveDir.exists()) {
            // 新建文件夹
            boolean b = saveDir.mkdirs();
        }
        // 循环文件进行存储
        for (MultipartFile file : files) {
            if (file != null) {
                // 拼接新的文件名
                String finalFilePath = FILE_ADDRESS + clientId + "/" + Objects.requireNonNull(file.getOriginalFilename()).trim();
                File saveFile = new File(finalFilePath);
                if (saveFile.exists()) {
                    // 已存在就删除之前的
                    boolean b = saveFile.delete();
                }
                try {
                    file.transferTo(saveFile);
                    picUrl.add(FILE_DOWNLOAD + finalFilePath);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.info("文件上传失败:" + e.getMessage());
                }
            }
        }
        return picUrl;
    }

    /**
     * 文件下载
     * @param response
     * @param fileUrl
     */
    public static void fileDowLoad(HttpServletResponse response, String fileUrl) {
        File file = new File(fileUrl);
        //文件输入流
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        //输出流
        OutputStream os;
        //判断文件父目录是否存在
        if (file.exists()) {
            try {
                response.setCharacterEncoding("UTF-8");
                String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                //设置中文文件名与后缀
                response.setContentType("application/force-download");
                //通过设置头信息给文件命名，也即是，在前端，文件流被接受完还原成原文件的时候会以你传递的文件名来命名
                response.addHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", URLEncoder.encode(fileName, "utf-8")));
                byte[] buffer = new byte[1024];
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将图片转为base64
     * @return
     */
    public static String changeBase64(String imgPath){
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(Objects.requireNonNull(data));
    }

}
